#coding:utf8
import datetime
import re
import app_setting
import hashlib
import time
import app_setting
import random,urllib2,urllib
import json
import socket


def randomStr(length):
	return ''.join(random.choice('0123456789abcdefhijklkmnopqrstuvwxyzABCDEFHIJKLKMNOPQRSTUVWXYZ') for n in range(length))

def deal_time_for_event_s(apply_start_time, apply_end_time, game_start_time, game_end_time,_type  = False):
	_now = datetime.datetime.now()
	__type = 3
	if apply_start_time > _now:
		status = '%s天后开放报名'%((apply_start_time - _now).days)
		__type = 4
	elif apply_start_time < _now and apply_end_time > _now:
		status ='报名中'
		__type = 1
	elif game_end_time and game_start_time and game_start_time < _now and game_end_time > _now:
		status = '比赛中'
		__type = 2
	elif  game_end_time and game_end_time < _now:
		status = '比赛结束'
		__type = 5
	elif game_start_time and game_start_time < _now:
		status = '等待开赛'
	else:
		status = '等待开赛'	
	if _type:
		return status,__type
	return status

def checkphone(phone):
	phone_check = re.compile('^(13\d|14[5|7]|15\d|166|17[3|6|7]|18\d)\d{8}$')
	res = re.search(phone_check, str(phone))
	if res:
		return True
	return False


def upload_file(file_content, file_key):
	if file_content:
		from qiniu import Auth, put_data
		q = Auth(app_setting.QINIUACCESS_KEY, app_setting.QINIUSECRET_KEY)
		token = q.upload_token(app_setting.QINIUBUCKET, file_key)
		ret, info = put_data(token, file_key, file_content)
		return ret


def md5_value(content):
	return hashlib.md5(content).hexdigest() 


## 返回赛事状态编码

def event_num(event_status):

	if event_status.find('天后开放报名')>-1:
		_type = 1
	elif event_status.find('报名中')>-1:
		_type = 2
	elif event_status.find('比赛中')>-1:
		_type = 3
	elif event_status.find('比赛结束')>-1:
		_type = 5
	else:
		_type = 4
	return _type
## 获取验证码
def check_image_authcode(validate):
	def gen_signature(params):
		params_str = ""
		for k in sorted(params.keys()):
			params_str += str(k)+ str(params[k])
		params_str += app_setting.WY_CAPTCHA['SECRET_KEY']
		return hashlib.md5(params_str).hexdigest()

	timestamp = int((time.time()) * 1000)
	paras = {
		"captchaId": app_setting.WY_CAPTCHA['ID'], 
		"validate": validate,
		"user": "",
		"secretId": app_setting.WY_CAPTCHA['SECRET_ID'],
		"version": "v2",
		"timestamp": str(timestamp),
		"nonce": random.randint(1, 999999),
	}
	signature = gen_signature(paras)
	paras["signature"] = signature
	req = urllib2.Request(url=app_setting.WY_CAPTCHA['VERIFY_URL'], data=urllib.urlencode(paras), \
	    headers={"Content-Type": "application/x-www-form-urlencoded"})
	res = urllib2.urlopen(req).read()
	try:
		res = json.loads(res)
	except ValueError:
		return "系统出错了，请稍候再试"
	if res.get("error") != 0:
		return "图片验证未通过"

	return ""
def randomNum(length):
    return ''.join(random.choice('0123456789') for n in range(length))